import React from 'react'
import { inject, observer } from 'mobx-react'
import { observable, action, toJS } from 'mobx'
import { WeaErrorPage, WeaTools, WeaEchart, WeaTop, WeaAlertPage, WeaTab, WeaRadioGroup,WeaButtonIcon } from 'ecCom'
import isEmpty from 'lodash/isEmpty'
import {WeaLocaleProvider} from 'ecCom';
import {Icon,Radio} from 'antd';
import * as ReportUtil from '../../util/report';
const getLabel = WeaLocaleProvider.getLabel;
const RadioGroup = Radio.Group;
let option={};
@inject('meetingReport')
@observer
class Report extends React.Component {
  constructor (props) {
    super(props)
    this.state = {}
  }
  
  componentWillMount () {
    const {meetingReport} = this.props
    meetingReport.isWillMount = true;
  }
  
  componentDidMount () {
    const {meetingReport} = this.props
    meetingReport.isInit = true;
    meetingReport.getUserDefInfo();
    meetingReport.getMyTheme();
  }
  
  
  componentDidUpdate () {
    const {meetingReport} = this.props
    const {absent, resolut, processd} = meetingReport
    if (!isEmpty(absent)) {
      if (this.refs.chart1) {
        // this.refs.chart1.clear();
        this.refs.chart1.paint()
        
      }
    }
    if (!isEmpty(resolut)) {
      if (this.refs.chart2) {
        // this.refs.chart2.clear();
        this.refs.chart2.paint()
      }
    }
    if (!isEmpty(processd)) {
      if (this.refs.chart3) {
        // this.refs.chart3.clear();
        this.refs.chart3.paint()
      }
    }
  }
  
  componentWillUnmount () {
    //组件卸载时一般清理一些状态
  }
  
  render () {
    const {meetingReport} = this.props
    let {loading, defdep, defsub, absent, resolut, processd, reporttab,absentType, themeFontSize} = meetingReport
    absent = toJS(absent)
    resolut = toJS(resolut)
    processd = toJS(processd)
    
    
    let option1 = '', option2 = '', option3 = ''
    if (reporttab==1 && !isEmpty(absent)) {
      option1 = {
        title: {
          x: 'center',
          text: getLabel(383341,"会议缺席次数统计排名"),
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}',
        },
        toolbox: {
          show: false,
          left:'95%',
          feature: {
            //dataView: {show: true, readOnly: false},
            //restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        label: {
          show: true,
          position: 'top',
        },
        grid: {
          borderWidth: 10,
          y: 80,
          y2: 60
        },
        xAxis: [
          {
            type: 'category',
            show: true,
            data: ['Line', 'Bar', 'Scatter', 'K', 'Pie', 'Radar', 'Chord', 'Force', 'Map', 'Gauge', 'Funnel'],
            axisLine: {//坐标轴
              show: true,
              lineStyle: {
                color: '#b2b2b2'
              }
            },
            axisTick: {//坐标轴刻度
              show: true,
            },
            axisLabel: {
              color: function (value, index) {
                return '#333'
              },
              formatter: function (val) {
                let arr = val.split('')
                if (arr.length > 15) {
                  arr.splice(5, 0, '\n')
                  arr.splice(11, 0, '\n')
                  arr.splice(17, 0, '\n')
                } else if (arr.length > 10) {
                  arr.splice(5, 0, '\n')
                  arr.splice(11, 0, '\n')
                } else if (arr.legth > 5) {
                  arr.splice(5, 0, '\n')
                }
                return arr.join('')
              }
            },
            nameTextStyle: {
              fontSize: themeFontSize, 
            }
            
          }
        ],
        yAxis: [
          {
            type: 'value',
            show: true,
            axisLine: {//坐标轴
              show: true,
              lineStyle: {
                color: '#b2b2b2'
              }
            },
            axisTick: {//坐标轴刻度
              show: true,
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#e2e2e2',
                type: 'dashed'
              },
            },
            axisLabel: {
              color: function (value, index) {
                return '#333'
              },
            },
            minInterval :1,
            nameTextStyle: {
              fontSize: themeFontSize, 
            }
          }
        ],
        series: [
          {
            name: getLabel(383341,"会议缺席次数统计排名"),
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  return WeaEchart.colors[params.dataIndex%10]
                },
              }
            },
          }
        ]
      }
      option1.series[0].data = absent.value || []
      option1.xAxis[0].data = absent.name || []
      option=option1;
    }
    if (reporttab==2 && !isEmpty(resolut)) {
      option2 = {
        title: {
          x: 'center',
          text: getLabel(383342,"会议决议提交情况"),
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          show: false,
          left:'95%',
          feature: {
            //dataView: {show: true, readOnly: false},
            //restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        label: {
          show: false,
          position: 'top',
        },
        legend: {
          data: [getLabel(383461,"已提交"), getLabel(15178,"未提交")],
          top: 10,
          left: '10%',
          textStyle: {
            fontSize: themeFontSize
          }
        },
        grid: {
          borderWidth: 10,
          // y: 80,
          // y2: 60
        },
        xAxis: [
          {
            type: 'category',
            show: true,
            data: ['Line', 'Bar', 'Scatter', 'K', 'Pie', 'Radar', 'Chord', 'Force', 'Map', 'Gauge', 'Funnel'],
            axisLine: {//坐标轴
              show: true,
              lineStyle: {
                color: '#b2b2b2'
              }
            },
            axisTick: {//坐标轴刻度
              show: true,
            },
            axisLabel: {
              color: function (value, index) {
                return '#333'
              },
              formatter: function (val) {
                let arr = val.split('')
                if (arr.length > 15) {
                  arr.splice(5, 0, '\n')
                  arr.splice(11, 0, '\n')
                  arr.splice(17, 0, '\n')
                } else if (arr.length > 10) {
                  arr.splice(5, 0, '\n')
                  arr.splice(11, 0, '\n')
                } else if (arr.legth > 5) {
                  arr.splice(5, 0, '\n')
                }
                return arr.join('')
              }
            },
            nameTextStyle: {
              fontSize: themeFontSize, 
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            show: true,
            axisLine: {//坐标轴
              show: true,
              lineStyle: {
                color: '#b2b2b2'
              }
            },
            axisTick: {//坐标轴刻度
              show: true,
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#e2e2e2',
                type: 'dashed'
              },
            },
            axisLabel: {
              color: function (value, index) {
                return '#333'
              },
            },
            minInterval :1,
            nameTextStyle: {
              fontSize: themeFontSize, 
            }
          }
        ],
        series: [
          {
            name: getLabel(383461,"已提交"),
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = '#4DB6C3'
                  return colorList
                },
              },
              
            },
          },
          {
            name: getLabel(15178,"未提交"),
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = '#E64C47'
                  return colorList
                },
              }
            },
          }
        
        ]
      }
      option2.series[0].data = resolut.value[0] || []//已提交
      option2.series[1].data = resolut.value[1] || []//未提交
      option2.xAxis[0].data = resolut.name
      option=option2;
    };
    if (reporttab==3 && !isEmpty(processd)) {
      option3 = {
        title: {
          x: 'center',
          text: getLabel(383365,"会议任务完成情况"),
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          show: false,
          left:'95%',
          feature: {
            //dataView: {show: true, readOnly: false},
            //restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        label: {
          show: false,
          position: 'top',
        },
        legend: {
          data: [getLabel(383462,"未开始"), getLabel(32556,"已延期"), getLabel(1960,"进行中"), getLabel(23774,"已完成")],
          top: 10,
          left: '10%',
          textStyle: {
            fontSize: themeFontSize
          }
        },
        grid: {
          borderWidth: 10,
          y: 80,
          y2: 60
        },
        xAxis: [
          {
            type: 'category',
            show: true,
            data: ['Line', 'Bar', 'Scatter', 'K', 'Pie', 'Radar', 'Chord', 'Force', 'Map', 'Gauge', 'Funnel'],
            axisLine: {//坐标轴
              show: true,
              lineStyle: {
                color: '#b2b2b2'
              }
            },
            axisTick: {//坐标轴刻度
              show: true,
            },
            axisLabel: {
              color: function (value, index) {
                return '#333'
              },
              formatter: function (val) {
                let arr = val.split('')
                if (arr.length > 15) {
                  arr.splice(5, 0, '\n')
                  arr.splice(11, 0, '\n')
                  arr.splice(17, 0, '\n')
                } else if (arr.length > 10) {
                  arr.splice(5, 0, '\n')
                  arr.splice(11, 0, '\n')
                } else if (arr.legth > 5) {
                  arr.splice(5, 0, '\n')
                }
                return arr.join('')
              }
            },
            nameTextStyle: {
              fontSize: themeFontSize, 
            }
            
          }
        ],
        
        yAxis: [
          {
            type: 'value',
            show: true,
            axisLine: {//坐标轴
              show: true,
              lineStyle: {
                color: '#b2b2b2'
              }
            },
            axisTick: {//坐标轴刻度
              show: true,
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#e2e2e2',
                type: 'dashed'
              },
            },
            axisLabel: {
              color: function (value, index) {
                return '#333'
              },
            },
            minInterval :1,
            nameTextStyle: {
              fontSize: themeFontSize, 
            }
          }
        ],
        textStyle: {
          color: '#000',
          'max-width': '20px',
          'width': '20px',
          maxWidth: '30px'
        },
        
        series: [
          {
            name: getLabel(383462,"未开始"),
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = '#FFCC00'
                  return colorList
                },
                
              }
            },
          },
          {
            name: getLabel(32556,"已延期"),
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = '#D50020'
                  return colorList
                },
                
              }
            },
          },
          {
            name: getLabel(1960,"进行中"),
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = '#8BCC52'
                  return colorList
                },
                
              }
            },
          },
          {
            name: getLabel(23774,"已完成"),
            type: 'bar',
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = '#1FC3E1'
                  return colorList
                },
                
              }
            },
          }
        
        ]
      }
      option3.series[0].data = processd.value[0] || []//未开始
      option3.series[1].data = processd.value[1] || []//已延期
      option3.series[2].data = processd.value[2] || []//进行中
      option3.series[3].data = processd.value[3] || []//已完成
      option3.xAxis[0].data = processd.name
      option=option3;
    }
    
    let topTab = [
      {
        title: getLabel(383366,"会议缺席统计"),
        viewcondition: 1
      },
      {
        title: getLabel(383367,"会议决议统计"),
        viewcondition: 2
      },
      {
        title: getLabel(383368,"会议任务统计"),
        viewcondition: 3
      }
    ]
    
    let config = [
      {
        label: getLabel(383464,"时间范围"),
        options: [
          {key: '2', showname: getLabel(15539,"本周")},
          {key: '3', showname: getLabel(130018,"本月"), selected: true},
          {key: '7', showname: getLabel(27347,"上个月")},
          {key: '4', showname: getLabel(383465,"本季")},
          {key: '9', showname: getLabel(383369,"上一季")},
          {key: '5', showname: getLabel(130017,"本年")},
          {key: '8', showname: getLabel(81716,"上一年")},
          {key: '6', showname: getLabel(32530,"指定日期范围")},
        ],
        domkey: ['timeSag'],
        selectLinkageDatas: {
          '6': {
            conditionType: 'RANGEPICKER',
            domkey: ['begindate', 'enddate'],
          }
        },
        labelcol: 3,
        fieldcol: 21,
      },
      {
        label: getLabel(383370,"数据统计范围"),
        options: [
          {key: '3', showname: getLabel(140,"总部")},
          {key: '1', showname: getLabel(131395,"分部"), selected: true},
          {key: '2', showname: getLabel(383371,"部门")},
        ],
        domkey: ['selectType'],
        selectLinkageDatas: {
          '1': {
            browserConditionParam: {
              'dataParams': {},
              'hasAddBtn': false,
              'hasAdvanceSerach': true,
              'isAutoComplete': 1,
              'isDetail': 0,
              'isMultCheckbox': false,
              'isSingle': true,
              // 'linkUrl': '/spa/hrm/engine.html#/hrmengine/organization?showTree=false&type=subcompany&id=',
              'tabs': [
                {
                  'dataParams': {
                    'list': '1'
                  },
                  'key': '1',
                  'name': getLabel(130619,"按列表"),
                  'selected': false
                },
                {
                  'key': '2',
                  'name': getLabel(18770,"按组织结构"),
                  'selected': false
                }
              ],
              'title': getLabel(131395,"分部"),
              'type': '164',
              'viewAttr': 2,
              'replaceDatas': [defsub] || []
            },
            conditionType: 'BROWSER',
            domkey: ['subIds'],
          },
          '2': {
            browserConditionParam: {
              'dataParams': {},
              'hasAddBtn': false,
              'hasAdvanceSerach': true,
              'isAutoComplete': 1,
              'isDetail': 0,
              'isMultCheckbox': false,
              'isSingle': true,
              // 'linkUrl': '/spa/hrm/engine.html#/hrmengine/organization?showTree=false&type=department&id=',
              'tabs': [
                {
                  'dataParams': {
                    'list': '1'
                  },
                  'key': '1',
                  'name': getLabel(130619,"按列表"),
                  'selected': false
                },
                {
                  'key': '2',
                  'name': getLabel(18770,"按组织结构"),
                  'selected': false
                }
              ],
              'title': getLabel(383371,"部门"),
              'type': '4',
              'viewAttr': 2,
              'replaceDatas': [defdep] || []
            },
            conditionType: 'BROWSER',
            domkey: ['depIds'],
          },
          
        },
        labelcol: 3,
        fieldcol: 21,
      },
    ]
    
    let bool = false;
    reporttab == 1 &&  option1 && option1.xAxis[0].data.length > 0 && (bool = true);
    reporttab == 2 &&  option2 && option2.xAxis[0].data.length > 0 && (bool = true);
    reporttab == 3 &&  option3 && option3.xAxis[0].data.length > 0 && (bool = true);

    return (
      <div className="meeting-report" style={{height: '100%'}}>
        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@0qt2c6`}
          loading={loading}
          icon={<i className='icon-coms-meeting'/>}
          iconBgcolor='#f14a2d'
          title={getLabel(383466,"会议报表")}
          buttons={[]}
          showDropIcon={false}
        >
          
          <div style={{margin: '16px'}} >
            <WeaRadioGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaRadioGroup@0ac03l`}
              config={config}
              onChange={(params) => {
                this.doChange(params)
              }}
              beforeInit = {//处理死循环问题
                (config, lastValueMap, cb) => {
                  cb(lastValueMap);
                }
              }
            />
          </div>
          
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@gro9ht`}
            className='meeting-report-weaTab'
            datas={topTab}
            keyParam="viewcondition"  //主键
            countParam="groupid" //数量
            type="card"
            selectedKey={reporttab}
            onChange={this.changeTab}
            buttons={bool && [<span className='icon-coms-download2' onClick = {this.downloadImg}/>]}
          />

          {reporttab == 1 &&
              <div className='meeting-report-tool-download'> 
                  <div className='meeting-report-tool'>
                    <RadioGroup ecId={`${this && this.props && this.props.ecId || ''}_RadioGroup@39p8bm`} onChange={this.onChangeRadio} value={absentType}>
                        <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@dde8x3`} value={1}>{getLabel(385331,"按会议签到统计")} </Radio>
                        <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@ec8qfx`} value={2}>{getLabel(385332,"按参会回执统计")} </Radio>
                    </RadioGroup>
                  </div>
              </div>
          }
            
          <div style={{position: 'relative', height: '555px', paddingTop: '30px', paddingRight: '30px' , backgroundColor: '#ffffff'}}>
            {
              reporttab == 1 &&
              (
                option1 && option1.xAxis[0].data.length > 0 ?
                  <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@d6kkz4`} ref="chart1" useDefault={false} option={option1}/>
                  : <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@fkotfy`} icon="icon-coms-blank">
                  <div>{getLabel(83553,"暂无数据")}</div>
                </WeaAlertPage>
              )
            }
            {
              reporttab == 2 && (
                option2 && option2.xAxis[0].data.length > 0 ?
                  <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@toauji`} ref="chart2" useDefault={false} option={option2}/>
                  : <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@1bsytg`} icon="icon-coms-blank">
                  <div>{getLabel(83553,"暂无数据")}</div>
                </WeaAlertPage>
              )
            }
            {
              reporttab == 3 &&
              (
                option3 && option3.xAxis[0].data.length > 0 ?
                  <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@co2uyq`} ref="chart3" useDefault={false} option={option3}/>
                  : <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@q9ugr3`} icon="icon-coms-blank">
                  <div>{getLabel(83553,"暂无数据")}</div>
                </WeaAlertPage>
              )
            }
          </div>
        </WeaTop>
      </div>
    )
  }
  
  
  downloadImg = ()=>{
    const {reporttab } = this.props.meetingReport;
    this.reporttab
    let echartid  ='';
    let name='Download';
    option&&option.title&&option.title.text&&(name=option.title.text);

    if(reporttab==1){
      echartid=this.refs.chart1.chart.id;
    }else if(reporttab==2){
      echartid=this.refs.chart2.chart.id;
    }else if(reporttab==3){
      echartid=this.refs.chart3.chart.id;
    }
    
    if(echartid!=''){
      const cvs = jQuery("div[_echarts_instance_='"+echartid+"'] canvas")[0];
      ReportUtil.downloadCvs2Img(cvs,name);
    }
  }
  
  onChangeRadio=(e)=>{
    const {setAbsentType,absentP,chartParams} = this.props.meetingReport;
    setAbsentType(e.target.value);
    absentP(chartParams)
  }

  doChange = (params) => {
    const {meetingReport} = this.props
    if(meetingReport.isWillMount){
      meetingReport.isWillMount = false;
      return;
    }else {
      let bool = true;
      params.depIds && params.depIds==0 && (params.depIds='');
      params.subIds && params.subIds==0 && (params.subIds='');
      params.timeSag && params.timeSag === '6' && !params.begindate && !params.enddate && (bool = false);
      params.selectType && params.selectType === '2' && !params.depIds && (bool = false);
      params.selectType && params.selectType === '1' && !params.subIds && (bool = false);


      bool && (meetingReport.chartParams = params);
      bool && meetingReport.chartPaint(meetingReport.chartParams);
    }
  }
  
  changeTab = (e) => {
    const {meetingReport} = this.props
    meetingReport.reporttab = e;
    meetingReport.changeReportTab(e)
  }
}

//组件检错机制
class MyErrorHandler extends React.Component {
  render () {
    const hasErrorMsg = this.props.error && this.props.error !== ''
    return (
      <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@5u6ll6`} msg={ hasErrorMsg ? this.props.error : getLabel(383324,"对不起，该页面异常，请联系管理员") }/>
    )
  }
}

Report = WeaTools.tryCatch(React, MyErrorHandler, {error: ''})(Report)

export default Report
